package com.lsj.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Controller
public class AuthorizeController {


    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/authorization_code")
    public String authorization(String code){
        MultiValueMap paramMap = new LinkedMultiValueMap();
        paramMap.add("client_id","2442280c8a8876c0706d");
        paramMap.add("client_secret","6e518d3a31ac1b71a08a5259a38f3a552eab4ee1");
        paramMap.add("code",code);
        paramMap.add("state","lsj");
        paramMap.add("redirect_uri","http://localhost:8080/authorization_code");
        Map<String,String> map = restTemplate.postForObject("https://github.com/login/oauth/access_token", paramMap, Map.class);
        System.out.println(map);
        String access_token = map.get("access_token");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization","token "+access_token);
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Map> exchange = restTemplate.exchange("https://api.github.com/user", HttpMethod.GET, httpEntity, Map.class);
        System.out.println("exchange.getBody() = " + exchange.getBody());
        return "redirect:/index.html";
    }
}
